import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/network_utils.dart';
import '../../components/toast_utils.dart';
import '../../manger/user_manger.dart';

class ChangePasswordPage extends StatefulWidget {
  const ChangePasswordPage({super.key});

  @override
  State<ChangePasswordPage> createState() => _ChangePasswordPageState();
}

class _ChangePasswordPageState extends State<ChangePasswordPage> {
  final TextEditingController _oldPasswordController = TextEditingController();
  final TextEditingController _newPasswordController = TextEditingController();
  final TextEditingController _confirmPasswordController = TextEditingController();

  Future<void> changePassword(BuildContext context) async {
    final localizations = AppLocalizations.of(context);
    
    if (_oldPasswordController.text.isEmpty) {
      ToastUtils.showCenterToast(context,'${localizations?.pleaseEnter}${localizations?.password}');
      return;
    }
    
    if (_newPasswordController.text.isEmpty || _confirmPasswordController.text.isEmpty) {
      ToastUtils.showCenterToast(context,'${localizations?.set}${localizations?.password}');
      return;
    }
    
    if (_newPasswordController.text != _confirmPasswordController.text) {
      ToastUtils.showCenterToast(context,'${localizations?.thePasswordsEnteredDoNotMatch}');
      return;
    }

     if (mounted) {
      ToastUtils.showLoadingToast(context);
    }
    
    final response = await NetworkUtils.post(
      RequestCmd.changePwd,
      body: {
        'password': _oldPasswordController.text,
        'newPassword': _newPasswordController.text
      },
    );
    
    ToastUtils.dismissLoadingToast();
    try {
      final responseData = response as Map<String, dynamic>;
      if (responseData['code'] == 200) {
        ToastUtils.showCenterToast(context, '${localizations?.changePassword}${localizations?.success}');
        UserInfos.shared.cleanUserInfos();
        if (mounted) {
          Navigator.popUntil(context, (route) => route.isFirst);
        }

      } else {
        ToastUtils.showCenterToast(context, responseData['msg'] ?? '${localizations?.changePassword}失败');
      }
    } catch (e) {
      ToastUtils.showCenterToast(context, '${localizations?.changePassword}失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        title: Text(localizations?.changePassword ?? 'Change Password',style: const TextStyle(fontSize: 17)),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
        child: Column(
          children: [
            // Old Password Input
            _buildInputContainer(
              label: '${localizations?.changePassword1}' ,
              controller: _oldPasswordController,
              hintText: '${localizations?.changePassword2}',
              topMargin: 20,
            ),
            
            // New Password Input
            _buildInputContainer(
              label: '${localizations?.changePassword3}',
              controller: _newPasswordController,
              hintText: '${localizations?.changePassword4}',
              topMargin: 40,
            ),
            
            // Confirm Password Input
            _buildInputContainer(
              label: '${localizations?.changePassword5}',
              controller: _confirmPasswordController,
              hintText: '${localizations?.changePassword6}',
              topMargin: 40,
            ),
            
            // Confirm Button
            Container(
              margin: const EdgeInsets.only(top: 40),
              width: double.infinity,
              height: 44,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF5D5FEE),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                ),
                onPressed: () {
                  changePassword(context);
                },
                child: Text(
                  localizations?.confirm ?? 'Confirm',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInputContainer({
    required String label,
    required TextEditingController controller,
    required String hintText,
    required double topMargin,
  }) {
    return Stack(
      children: [
        Container(
          margin: EdgeInsets.only(top: topMargin),
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: const Color(0xFFD2D2D2)),
          ),
          child: TextField(
            controller: controller,
            obscureText: true,
            decoration: InputDecoration(
              hintText: hintText,
              hintStyle: const TextStyle(
                color: Color(0xFF666666),
                fontSize: 15,
              ),
              border: InputBorder.none,
              contentPadding: EdgeInsets.zero,
            ),
            style: const TextStyle(
              color: Colors.black,
              fontSize: 15,
            ),
          ),
        ),
        Positioned(
          left: 45,
          top: topMargin - 12,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(5),
            ),
            child: Text(
              label,
              style: const TextStyle(
                color: Color(0xFF666666),
                fontSize: 15,
              ),
            ),
          ),
        ),
      ],
    );
  }
}